package com.vn.toaa.karaoke.ui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;

import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.startapp.android.publish.StartAppAd.AdMode;
import com.vn.toaa.karaoke.database.DatabaseManager;
import com.vn.toaa.karaoke.database.SongModel;
import com.vn.toaa.karaoke.ui.AlphabetListAdapter.Item;
import com.vn.toaa.karaoke.ui.AlphabetListAdapter.Row;
import com.vn.toaa.karaoke.ui.AlphabetListAdapter.Section;
import com.vn.toaa.karaoke.ui.ClearableEditText.IAfterTextChangedListener;
import com.vn.toaa.karaoke.ui.Constant.SearchType;
import com.vn.toaa.karaoke.ui.Constant.SongCollection;
import com.vn.toaa.karaoke.ui.Constant.SongType;
import com.vn.toaa.karaokecodelist.R;

public class MainActivity extends BaseAdsActivity implements IAfterTextChangedListener, OnClickListener {

	public static final String TAG = MainActivity.class.getSimpleName();
	private ListView mLvSong;
	private Spinner mSpSongCollection;
	private Spinner mSpSongType;
	private Spinner mSpLetterGroup;
	private Spinner mSpSearchType;
	private TextView mTvNotification;
	private ClearableEditText mEdSearch;
    private AlphabetListAdapter adapter = new AlphabetListAdapter();
    private GestureDetector mGestureDetector;
    private List<Object[]> alphabet = new ArrayList<Object[]>();
    private HashMap<String, Integer> sections = new HashMap<String, Integer>();
    private int sideIndexHeight;
    private static float sideIndexX;
    private static float sideIndexY;
    private int indexListSize;
    
    private List<SongModel> mSongModels;
    private int mSongCollection = SongCollection.FIVE_NUMBER.ordinal();
    private int mSongType = SongType.ALL.ordinal();
    private int mSearchType = SearchType.ALL.ordinal();
    private SearchKeywordAsync mSearchKeywordAsync;
    private ChangeSongGroupAsync mChangeSongGroupAsync;
	private List<Row> mRows;
    
    class SideIndexGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            sideIndexX = sideIndexX - distanceX;
            sideIndexY = sideIndexY - distanceY;

            if (sideIndexX >= 0 && sideIndexY >= 0) {
                displayListItem();
            }

            return super.onScroll(e1, e2, distanceX, distanceY);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        mLvSong = (ListView) findViewById(R.id.listivew_song);
        mLvSong.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(final AdapterView<?> parent, View view, final int position, long id) {
				runOnUiThread(new Runnable() {
					public void run() {
						if (parent.getAdapter().getItem(position) instanceof Item) {
							Intent intent = new Intent(MainActivity.this, DetailActivity.class);
							intent.putExtra(Constant.EXTRA_SONG_ID, ((Item) parent.getAdapter().getItem(position)).mSongId);
							intent.putExtra(Constant.EXTRA_SONG_COLLECTION, mSongCollection);
							startActivity(intent);
						}
					}
				});
			}
		});
        mSpSongCollection = (Spinner) findViewById(R.id.spinner_song_collection);
        mSpSongType = (Spinner) findViewById(R.id.spinner_song_type);
        mSpLetterGroup = (Spinner) findViewById(R.id.spinner_letter_group);
        mSpSearchType = (Spinner) findViewById(R.id.spinner_search_type);
        mTvNotification = (TextView) findViewById(R.id.textview_notification);
        mEdSearch = (ClearableEditText) findViewById(R.id.edittext_search);
        mEdSearch.setIAfterTextChangedListener(this);
        final Button btSearch = (Button) findViewById(R.id.button_search);
        final Button btFavorite = (Button) findViewById(R.id.button_favorite);
        final Button btRefresh = (Button) findViewById(R.id.button_refresh);
        final TextView tvTitle = (TextView) findViewById(R.id.textview_title);
        btFavorite.setOnClickListener(this);
        btRefresh.setOnClickListener(this);
        btSearch.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (mEdSearch.isShown()) {
					mEdSearch.setText("");
					mEdSearch.setVisibility(View.GONE);
					tvTitle.setVisibility(View.VISIBLE);
					btFavorite.setVisibility(View.VISIBLE);
					btRefresh.setVisibility(View.VISIBLE);
					mSpSongType.setVisibility(View.VISIBLE);
//					mSpLetterGroup.setVisibility(View.VISIBLE);
					mSpSearchType.setVisibility(View.GONE);
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(mEdSearch.getWindowToken(), 0);
				} else {
					mEdSearch.setVisibility(View.VISIBLE);
					mEdSearch.requestFocus();
					tvTitle.setVisibility(View.GONE);
					btFavorite.setVisibility(View.GONE);
					btRefresh.setVisibility(View.GONE);
					mSpSongType.setVisibility(View.GONE);
//					mSpLetterGroup.setVisibility(View.GONE);
					mSpSearchType.setVisibility(View.VISIBLE);
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.showSoftInput(mEdSearch, 0);
				}
			}
		});
        
		ArrayAdapter<String> spCollectionAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
				Constant.ARR_SONG_COLLECTION);
		spCollectionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		ArrayAdapter<String> spTypeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,
				Constant.ARR_SONG_TYPE);
		spTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		ArrayAdapter<String> spSearchTypeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, Constant.ARR_SEARCH_TYPE);
		spSearchTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		
		mSpSongCollection.setAdapter(spCollectionAdapter);
		mSpSongType.setAdapter(spTypeAdapter);
		mSpSearchType.setAdapter(spSearchTypeAdapter);
		mSpSongType.setSelection(0);
		mSpSongCollection.setSelection(0);
		mSpSearchType.setSelection(0);
        mSpSongCollection.setOnItemSelectedListener(new OnItemSelectedListener() {
        	
        	private boolean mIsFirstTime = true;

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				Log.i(TAG, "mSpSongCollection onItemSelected: " + position);
				if (!mIsFirstTime) {
					mSongCollection = position;
					if (!mEdSearch.isShown()) {
						if (mChangeSongGroupAsync != null) {
							mChangeSongGroupAsync.cancel(true);
						}
						mChangeSongGroupAsync = new ChangeSongGroupAsync();
						mChangeSongGroupAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
					} else {
						onAfterTextChanged();
					}
				}
				setHintTextSearch();
				mIsFirstTime = false;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
        
        mSpSongType.setOnItemSelectedListener(new OnItemSelectedListener() {
        	
        	private boolean mIsFirstTime = true;

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				Log.i(TAG, "mSpSongType onItemSelected: " + position);
				if (!mIsFirstTime) {
					mSongType = position;
					if (mChangeSongGroupAsync != null) {
						mChangeSongGroupAsync.cancel(true);
					}
			        mChangeSongGroupAsync = new ChangeSongGroupAsync();
			        mChangeSongGroupAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
				}
				mIsFirstTime = false;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
        mSpLetterGroup.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				if (position > -1 && position < alphabet.size()) {
					Object[] indexItem = alphabet.get(position);
					int subitemPosition = sections.get(indexItem[0]);
					mLvSong.setSelection(subitemPosition);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
        mSpSearchType.setOnItemSelectedListener(new OnItemSelectedListener() {
        	
        	private boolean mIsFirstTime = true;

			@Override
			public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
				if (!mIsFirstTime) {
					mSearchType = position;
					setHintTextSearch();
					onAfterTextChanged();
				}
				mIsFirstTime = false;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
        
        DatabaseManager.getInstance().openConnection();
        mGestureDetector = new GestureDetector(this, new SideIndexGestureListener());

        if (mChangeSongGroupAsync != null) {
			mChangeSongGroupAsync.cancel(true);
		}
        mChangeSongGroupAsync = new ChangeSongGroupAsync();
        mChangeSongGroupAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
        
		// show ads
		showExitAdWhenBack();
		new Handler().postDelayed(new Runnable() {
			public void run() {
				showInterstitialAd(AdMode.AUTOMATIC);
			}
		}, 1000);
    }
    
    /**
     * 
     */
    private void setHintTextSearch() {
		if (mSongCollection == SongCollection.FIVE_NUMBER.ordinal()) {
			if (mSearchType == SearchType.ALL.ordinal()) {
				mEdSearch.setHintText("Tìm kiếm bài hát 5 số");
			} else if (mSearchType == SearchType.CODE.ordinal()) {
				mEdSearch.setHintText("Tìm kiếm bài hát 5 số theo mã số");
			} else if (mSearchType == SearchType.NAME.ordinal()) {
				mEdSearch.setHintText("Tìm kiếm bài hát 5 số theo tên bài");
			} else if (mSearchType == SearchType.AUTHOR.ordinal()) {
				mEdSearch.setHintText("Tìm kiếm bài hát 5 số theo tên tác giả");
			} else {
				mEdSearch.setHintText("Tìm kiếm bài hát 5 số theo lời");
			}
		} else if (mSongCollection == SongCollection.SIX_NUMBER.ordinal()) {
			if (mSearchType == SearchType.ALL.ordinal()) {
				mEdSearch.setHintText("Tìm kiếm bài hát 6 số");
			} else if (mSearchType == SearchType.CODE.ordinal()) {
				mEdSearch.setHintText("Tìm kiếm bài hát 6 số theo mã số");
			} else if (mSearchType == SearchType.NAME.ordinal()) {
				mEdSearch.setHintText("Tìm kiếm bài hát 6 số theo tên bài");
			} else if (mSearchType == SearchType.AUTHOR.ordinal()) {
				mEdSearch.setHintText("Tìm kiếm bài hát 6 số theo tên tác giả");
			} else {
				mEdSearch.setHintText("Tìm kiếm bài hát 6 số theo lời");
			}
		}
	}

    /**
     * Initialize ListView and Navigation view
     */
	private void initViews(boolean shouldSort) {
        if (mSongModels == null) {
			return;
		}
        if (shouldSort) {
        	Collections.sort(mSongModels);
		}
		alphabet = new ArrayList<Object[]>();
        mRows = new ArrayList<Row>();
        int start = 0;
        int end = 0;
        String previousLetter = null;
        Object[] tmpIndexItem = null;
        Pattern numberPattern = Pattern.compile("[0-9]");

        for (SongModel songModel : mSongModels) {
            String firstLetter = songModel.getTitleAbbr().substring(0, 1).toUpperCase();
            if (Arrays.asList(Constant.GROUP_A).contains(firstLetter)) {
				firstLetter = "A";
			} else if (Arrays.asList(Constant.GROUP_D).contains(firstLetter)) {
				firstLetter = "D";
			} else if (Arrays.asList(Constant.GROUP_E).contains(firstLetter)) {
				firstLetter = "E";
			} else if (Arrays.asList(Constant.GROUP_O).contains(firstLetter)) {
				firstLetter = "O";
			} else if (Arrays.asList(Constant.GROUP_U).contains(firstLetter)) {
				firstLetter = "U";
			}

            // Group numbers together in the scroller
            if (numberPattern.matcher(firstLetter).matches()) {
                firstLetter = "#";
            }

            // If we've changed to a new letter, add the previous letter to the alphabet scroller
            if (previousLetter != null && !firstLetter.equals(previousLetter)) {
                end = mRows.size() - 1;
                tmpIndexItem = new Object[3];
                tmpIndexItem[0] = previousLetter.toUpperCase(Locale.UK);
                tmpIndexItem[1] = start;
                tmpIndexItem[2] = end;
                alphabet.add(tmpIndexItem);

                start = end + 1;
            }

            // Check if we need to add a header row
            if (!firstLetter.equals(previousLetter)) {
                mRows.add(new Section(firstLetter));
                sections.put(firstLetter, start);
            }

            // Add the country to the list
			mRows.add(new Item(songModel.getSongId(), songModel.getTitle(), songModel.getLyric(), false));
            previousLetter = firstLetter;
        }

        if (previousLetter != null) {
            // Save the last letter
            tmpIndexItem = new Object[3];
            tmpIndexItem[0] = previousLetter.toUpperCase(Locale.UK);
            tmpIndexItem[1] = start;
            tmpIndexItem[2] = mRows.size() - 1;
            alphabet.add(tmpIndexItem);
        }

	}
	
	/**
	 * Refresh ListView and Navigation view on UI thread
	 */
	private void refreshListView() {
		runOnUiThread(new Runnable() {
			public void run() {
				adapter.setRows(mRows);
				mLvSong.setAdapter(adapter);
//				updateList();
				
				if (alphabet == null || alphabet.size() <= 0) {
					mSpLetterGroup.setVisibility(View.GONE);
				} else {
					final List<String> letterList = new ArrayList<String>();
					for (int i = 0; i < alphabet.size(); i++) {
						letterList.add(alphabet.get(i)[0].toString());
					}
					final ArrayAdapter<String> spLetterGroupAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_item, letterList);
					spLetterGroupAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					mSpLetterGroup.setAdapter(spLetterGroupAdapter);
					mSpLetterGroup.setVisibility(View.VISIBLE);
				}
				
				if (mSongModels == null || mSongModels.size() <= 0) {
					mLvSong.setVisibility(View.GONE);
					mTvNotification.setVisibility(View.VISIBLE);
				} else {
					mLvSong.setVisibility(View.VISIBLE);
					mTvNotification.setVisibility(View.GONE);
				}
			}
		});
	}
	
    /**
     * Initialize data when changing by Spinner
     */
    private void initData() {
    	if (mSongCollection == SongCollection.FIVE_NUMBER.ordinal()){
			if (mSongType == SongType.ALL.ordinal()){
				mSongModels = ValueContainer.getInstance().getSongModelsInFive();
			} else if (mSongType == SongType.ENGLISH.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByLanguageInFive(1);
			} else if (mSongType == SongType.VIETNAMESE.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByLanguageInFive(0);
			} else if (mSongType == SongType.VOL_37.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(37);
			} else if (mSongType == SongType.VOL_38.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(38);
			} else if (mSongType == SongType.VOL_39.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(39);
			} else if (mSongType == SongType.VOL_40.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(40);
			} else if (mSongType == SongType.VOL_41.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(41);
			} else if (mSongType == SongType.VOL_42.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(42);
			} else if (mSongType == SongType.VOL_43.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(43);
			} else if (mSongType == SongType.VOL_44.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(44);
			} else if (mSongType == SongType.VOL_45.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(45);
			} else if (mSongType == SongType.VOL_46.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(46);
			} else if (mSongType == SongType.VOL_47.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(47);
			} else if (mSongType == SongType.VOL_48.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(48);
			} else if (mSongType == SongType.VOL_49.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(49);
			} else if (mSongType == SongType.VOL_50.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(50);
			} else if (mSongType == SongType.VOL_51.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInFive(51);
			}
		} else if (mSongCollection == SongCollection.SIX_NUMBER.ordinal()){
			if (mSongType == SongType.ALL.ordinal()){
				mSongModels = ValueContainer.getInstance().getSongModelsInSix();
			} else if (mSongType == SongType.ENGLISH.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByLanguageInSix(1);
			} else if (mSongType == SongType.VIETNAMESE.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByLanguageInSix(0);
			} else if (mSongType == SongType.VOL_37.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(37);
			} else if (mSongType == SongType.VOL_38.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(38);
			} else if (mSongType == SongType.VOL_39.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(39);
			} else if (mSongType == SongType.VOL_40.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(40);
			} else if (mSongType == SongType.VOL_41.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(41);
			} else if (mSongType == SongType.VOL_42.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(42);
			} else if (mSongType == SongType.VOL_43.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(43);
			} else if (mSongType == SongType.VOL_44.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(44);
			} else if (mSongType == SongType.VOL_45.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(45);
			} else if (mSongType == SongType.VOL_46.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(46);
			} else if (mSongType == SongType.VOL_47.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(47);
			} else if (mSongType == SongType.VOL_48.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(48);
			} else if (mSongType == SongType.VOL_49.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(49);
			} else if (mSongType == SongType.VOL_50.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(50);
			} else if (mSongType == SongType.VOL_51.ordinal()){
				mSongModels = DatabaseManager.getInstance().selectSongByVolInSix(51);
			}
		}
	}
    
    @Override
    protected void onResume() {
    	super.onResume();
    	mEdSearch.setIAfterTextChangedListener(this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (mGestureDetector.onTouchEvent(event)) {
            return true;
        } else {
            return false;
        }
    }

    public void updateList() {
        LinearLayout sideIndex = (LinearLayout) findViewById(R.id.sideIndex);
        sideIndex.removeAllViews();
        indexListSize = alphabet.size();
        if (indexListSize < 1) {
            return;
        }

        int indexMaxSize = (int) Math.floor(sideIndex.getHeight() / 20);
        int tmpIndexListSize = indexListSize;
        while (tmpIndexListSize > indexMaxSize) {
            tmpIndexListSize = tmpIndexListSize / 2;
        }
        double delta;
        if (tmpIndexListSize > 0) {
            delta = indexListSize / tmpIndexListSize;
        } else {
            delta = 1;
        }

        TextView tmpTV;
        for (double i = 1; i <= indexListSize; i = i + delta) {
            Object[] tmpIndexItem = alphabet.get((int) i - 1);
            String tmpLetter = tmpIndexItem[0].toString();

            tmpTV = new TextView(this);
            tmpTV.setText(tmpLetter);
            tmpTV.setGravity(Gravity.CENTER);
            tmpTV.setTextSize(15);
            tmpTV.setTextColor(Color.BLACK);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1);
            tmpTV.setLayoutParams(params);
            sideIndex.addView(tmpTV);
        }

        sideIndexHeight = sideIndex.getHeight();

        sideIndex.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // now you know coordinates of touch
                sideIndexX = event.getX();
                sideIndexY = event.getY();

                // and can display a proper item it country list
                displayListItem();

                return false;
            }
        });
    }

    public void displayListItem() {
        LinearLayout sideIndex = (LinearLayout) findViewById(R.id.sideIndex);
        sideIndexHeight = sideIndex.getHeight();
        // compute number of pixels for every side index item
        double pixelPerIndexItem = (double) sideIndexHeight / indexListSize;

        // compute the item index for given event position belongs to
        int itemPosition = (int) (sideIndexY / pixelPerIndexItem);
        
		for (int i = 0; i < sideIndex.getChildCount(); i++) {
			if (i == itemPosition) {
				View view = sideIndex.getChildAt(itemPosition);
				if (view != null && view instanceof TextView) {
					((TextView) view).setTextColor(Color.WHITE);
				}
			} else {
				View view = sideIndex.getChildAt(i);
				if (view != null && view instanceof TextView) {
					((TextView) view).setTextColor(Color.BLACK);
				}
			}
		}

        // get the item (we can do it since we know item index)
        if (itemPosition < alphabet.size()) {
            Object[] indexItem = alphabet.get(itemPosition);
            int subitemPosition = sections.get(indexItem[0]);

            //ListView listView = (ListView) findViewById(android.R.id.list);
            mLvSong.setSelection(subitemPosition);
        }
    }
    
    class SearchKeywordAsync extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {
			if (isCancelled()) {
				return null;
			}
			final String searchString = params[0].toLowerCase();
			if (!searchString.isEmpty()) {
				if (mSongCollection == SongCollection.FIVE_NUMBER.ordinal()) {
					searchByKeywordInFive(searchString);
				} else {
					searchByKeywordInSix(searchString);
				}
			} else {
				initData();
			}
			initViews(true);
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			Log.i(TAG, "onPostExecute search");
			if (isCancelled()) {
				return;
			}
			refreshListView();
		}
		
		private void searchByKeywordInFive(String keyword) {
			mSongModels = new ArrayList<SongModel>();
			final List<SongModel> songInFive = ValueContainer.getInstance().getSongModelsInFive();
			if (songInFive != null) {
				for (int i = songInFive.size() - 1; i >= 0; i--) {
					if (isCancelled()) {
						return;
					}
					final SongModel songModel = songInFive.get(i);
					final String songId = String.valueOf(songModel.getSongId()).toLowerCase();
					final String songTitle = songModel.getTitle().toLowerCase();
					final String songTitleSearch = songModel.getTitleSearch().toLowerCase();
					final String songLyric = songModel.getLyric().toLowerCase();
					final String songLyricSearch = songModel.getLyricSearch().toLowerCase();
					final String songAuthor = songModel.getAuthor().toLowerCase();
					final String songAuthorSearch = songModel.getAuthorSearch().toLowerCase();
					if (mSearchType == SearchType.ALL.ordinal()) {
						if (songId.contains(keyword) || songTitle.contains(keyword) || songTitleSearch.contains(keyword)
								|| songLyric.contains(keyword) || songLyricSearch.contains(keyword)
								|| songAuthor.contains(keyword) || songAuthorSearch.contains(keyword)) {
							mSongModels.add(songModel);
						}
					} else if (mSearchType == SearchType.CODE.ordinal()) {
						if (songId.contains(keyword)) {
							mSongModels.add(songModel);
						}
					} else if (mSearchType == SearchType.NAME.ordinal()) {
						if (songTitle.contains(keyword) || songTitleSearch.contains(keyword)) {
							mSongModels.add(songModel);
						}
					} else if (mSearchType == SearchType.AUTHOR.ordinal()) {
						if (songAuthor.contains(keyword) || songAuthorSearch.contains(keyword)) {
							mSongModels.add(songModel);
						}
					} else if (mSearchType == SearchType.LYRIC.ordinal()) {
						if (songLyric.contains(keyword) || songLyricSearch.contains(keyword)) {
							mSongModels.add(songModel);
						}
					}
				}
			}
		}
		
		private void searchByKeywordInSix(String keyword) {
			mSongModels = new ArrayList<SongModel>();
			final List<SongModel> songInSix = ValueContainer.getInstance().getSongModelsInSix();
			if (songInSix != null) {
				for (int i = songInSix.size() - 1; i >= 0; i--) {
					if (isCancelled()) {
						return;
					}
					final SongModel songModel = songInSix.get(i);
					final String songId = String.valueOf(songModel.getSongId()).toLowerCase();
					final String songTitle = songModel.getTitle().toLowerCase();
					final String songTitleSearch = songModel.getTitleSearch().toLowerCase();
					final String songLyric = songModel.getLyric().toLowerCase();
					final String songLyricSearch = songModel.getLyricSearch().toLowerCase();
					final String songAuthor = songModel.getAuthor().toLowerCase();
					final String songAuthorSearch = songModel.getAuthorSearch().toLowerCase();
					if (mSearchType == SearchType.ALL.ordinal()) {
						if (songId.contains(keyword) || songTitle.contains(keyword) || songTitleSearch.contains(keyword)
								|| songLyric.contains(keyword) || songLyricSearch.contains(keyword)
								|| songAuthor.contains(keyword) || songAuthorSearch.contains(keyword)) {
							mSongModels.add(songModel);
						}
					} else if (mSearchType == SearchType.CODE.ordinal()) {
						if (songId.contains(keyword)) {
							mSongModels.add(songModel);
						}
					} else if (mSearchType == SearchType.NAME.ordinal()) {
						if (songTitle.contains(keyword) || songTitleSearch.contains(keyword)) {
							mSongModels.add(songModel);
						}
					} else if (mSearchType == SearchType.AUTHOR.ordinal()) {
						if (songAuthor.contains(keyword) || songAuthorSearch.contains(keyword)) {
							mSongModels.add(songModel);
						}
					} else if (mSearchType == SearchType.LYRIC.ordinal()) {
						if (songLyric.contains(keyword) || songLyricSearch.contains(keyword)) {
							mSongModels.add(songModel);
						}
					}
				}
			}
		}
    }
    
    class ChangeSongGroupAsync extends AsyncTask<Void, Void, Void> {
    	
		@Override
		protected Void doInBackground(Void... params) {
			Log.i(TAG, "ChangeSongGroupAsync doInBackground");
			initData();
			initViews(true);
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			Log.i(TAG, "ChangeSongGroupAsync onPostExecute");
			mEdSearch.setText("");
			refreshListView();
		}
    }
    
    @Override
    public void onBackPressed() {
    	displayExitDialog();
    }

    @Override
    protected void onDestroy() {
    	DatabaseManager.getInstance().closeConnection();
    	super.onDestroy();
    }

	@Override
	public void onAfterTextChanged() {
		if (mEdSearch.isShown()) {
			if (mSearchKeywordAsync != null) {
				mSearchKeywordAsync.cancel(true);
			}
			mSearchKeywordAsync = new SearchKeywordAsync();
			mSearchKeywordAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, mEdSearch.getText().toString());
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_favorite:
			startActivity(new Intent(this, FavoriteActivity.class));
			break;
		case R.id.button_refresh:
			if (mSearchKeywordAsync != null) {
				mSearchKeywordAsync.cancel(true);
			}
			mSearchKeywordAsync = new SearchKeywordAsync();
			mSearchKeywordAsync.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, mEdSearch.getText().toString());
			break;
		default:
			break;
		}
	}
	
	private void displayExitDialog() {
		final Builder builder = new Builder(this);
		builder.setTitle("Select options");
		builder.setItems(new String[] { "Đánh giá", "Thêm ứng dụng", "Chia sẻ", "Thoát" }, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case 0:
					try {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						String uriString = String.format("market://details?id=%s", getPackageName());
						intent.setData(Uri.parse(uriString));
						startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				case 1:
					try {
						Intent intent = new Intent(Intent.ACTION_VIEW);
						String uriString = String.format("market://search?q=pub:%s", Constant.PUBLISHER_NAME);
						intent.setData(Uri.parse(uriString));
						startActivity(intent);
					} catch (Exception e) {
						e.printStackTrace();
					}
					break;
				case 2:
					final Intent intent = new Intent(Intent.ACTION_SEND);
					intent.setType("text/plain");
					intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_message));
					try {
						startActivity(Intent.createChooser(intent, "Select an action"));
					} catch (android.content.ActivityNotFoundException ex) {
						// (handle error)
					}
					break;
				case 3:
					finish();
					break;
				default:
					break;
				}
			}
		});
		builder.create().show();
	}
	
}
